package zondy.yapi.extProject.config;

import com.mongodb.client.model.changestream.FullDocument;
import org.bson.Document;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.messaging.ChangeStreamRequest;
import org.springframework.data.mongodb.core.messaging.DefaultMessageListenerContainer;
import org.springframework.data.mongodb.core.messaging.MessageListenerContainer;
import org.springframework.data.mongodb.core.query.Criteria;
import zondy.yapi.extProject.messageListener.DocumentMessageListener;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static org.springframework.data.mongodb.core.aggregation.Aggregation.match;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation;

/**
 * mongo配置
 *
 * @author 管子
 * @date 2024/7/30 21:32
 * @description: MongoConfig 类
 */
@Configuration
public class MongoConfig {

    /**
     * 注册文档监听器
     *
     * @param mongoTemplate mongo连接操作类
     * @param documentMessageListener 默认的文档监听处理器
     * @return
     */
    @Bean
    public MessageListenerContainer messageListenerContainer(MongoTemplate mongoTemplate, DocumentMessageListener documentMessageListener) {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        // 自动启动
        DefaultMessageListenerContainer defaultMessageListenerContainer = new DefaultMessageListenerContainer(mongoTemplate, executor) {
            @Override
            public boolean isAutoStartup() {
                return true;
            }
        };

        ChangeStreamRequest<Document> request = ChangeStreamRequest.builder(documentMessageListener)
                // 需要监听的集合名，不指定默认监听数据库的
                .collection("log")
                // 过滤需要监听的操作类型
                .filter(newAggregation(match(Criteria.where("operationType").in("insert"))))
                // 不设置时，文档更新时，只会发送变更字段的信息
                .fullDocumentLookup(FullDocument.UPDATE_LOOKUP)
                .build();
        defaultMessageListenerContainer.register(request, Document.class);
        return defaultMessageListenerContainer;
    }

}
